/* 各个流程使用 */
(function($) {
    // 产品绑定厂家时选择厂家后更新产品autocomplete
    $.productEnabled = function(obj) {
        var factory_id = parseInt(obj.value);
        $(obj.form).find("input[name*='product_no]']").val('').prev().val('');
        var where = "factory_id=" + factory_id;
        $(obj.form).find("input[name*='product_no]']").removeAttr("disabled").removeClass("disabled").attr({"where": where, "jqac": true})
                .each(function() {
            $(this).initAutocomplete();
        })
    }
    $.productEnabledForLc = function(obj) {
        var factory_id = parseInt(obj.value);
        var where = "factory_id=" + factory_id;
        $(obj).parents("tr:first").find("input[name*='product_no]']").removeAttr("disabled").removeClass("disabled").attr({"where": where, "jqac": true}).initAutocomplete();
    }
    // 产品绑定颜色时选择产品后更新颜色autocomplete
    $.colorEnabled = function(obj) {
        var product_id = parseInt(obj.value);
        $(obj).parents("tr:first").find("input[name='color_name']").val('').prev().val('');
        if (product_id > 0) {
            var ids;
            $.ajax({
                type: "POST",
                url: APP + "/Ajax/getProductColorId",
                data: "id=" + product_id,
                dataType: "text",
                cache: false,
                async: false,
                success: function(result) {
                    ids = result
                }
            });
            var where = "id in(" + ids + ")";
            $(obj).parents("tr:first").find("input[name='color_name']").removeAttr("disabled").removeClass("disabled").attr({"where": where, "jqac": true}).each(function() {
                $(this).initAutocomplete();
            })
        }
    }

    // 产品绑定尺码时选择产品后更新尺码autocomplete
    $.sizeEnabled = function(obj) {
        var product_id = parseInt(obj.value);
        $(obj).parents("tr:first").find("input[name='size_name']").val('').prev().val('');
        if (product_id > 0) {
            var ids;
            $.ajax({
                type: "POST",
                url: APP + "/Ajax/getProductSizeId",
                data: "id=" + product_id,
                dataType: "text",
                cache: false,
                async: false,
                success: function(result) {
                    ids = result
                }
            });
            var where = "id in(" + ids + ")";
            $(obj).parents("tr:first").find("input[name='size_name']").removeAttr("disabled").removeClass("disabled").attr({"where": where, "jqac": true}).each(function() {
                $(this).initAutocomplete();
            })
        }
    }
    // 添加快捷菜单
    $.shortcutMenu = function(obj, m, a) {
        var url = $(obj).attr("url");
        $.post(url, {model: m, action: a}, function(state) {
            if (state > 0) {
                $.resetShortcutMenu();
            }
        });
    }
    // 重载快捷菜单
    $.resetShortcutMenu = function() {
        var w = $(window).width();
        if (w < 1280) {
            var i = 2;
        } else if (w < 1366) {
            var i = 4;
        } else {
            var i = 5;
        }
        $("#shortcutMenu").load(APP + '/Ajax/loadShortcutMenu/mt/' + i, function() {
            $("#sdfjasdlfasdf").mouseover(function() {
                $('#shortMenuHide').fadeIn(200)
            });
            $("#shortMenuHide").mouseout(function() {
                $('#shortMenuHide').hide()
            });
            $("#shortMenuHide ul li").mouseover(function() {
                $('#shortMenuHide').show()
            });
        })
    }
    // 显示进度条
    $.loading = function(obj) {
        $("#s_loading").show();
    };
    $.removeLoading = function() {
        $dom.find("input[type='submit']").removeAttr("disabled");
        $("#s_loading").hide();
    }
    $.quicklyAdd = function(module, type) {
        $("#dialog-quickly_add").remove();
        $('<div id="dialog-quickly_add"></div>').load('index.php/QuicklyOperate/' + module + '/type/' + type, function() {
            var quick_dom = $(this);
            $(this).find("form").sendForm({"dataType": "json", "success": function(result, statusText, xhr, $form) {
                    if (result.status == 1) {
                        quicklyAddCallback(module, result);
                        $("#dialog-quickly_add").dialog("destroy");
                    } else if (result.status == 2) {
                        var oft = $("#dialog-quickly_add").offset();
                        validity(result.info, quick_dom, '.table_autoshow', 0, oft.left);
                    } else {
                        $("<div>" + result.info + "</div>").dialog({
                            modal: true,
                            resizable: false,
                            buttons: {
                                Ok: function() {
                                    $(this).remove();
                                }
                            }
                        });
                    }
                    clearTimeout(removeLoadTime);
                    var removeLoadTime = setTimeout($.removeLoading, 150);
                }});
            $(this).find("input[jqac]").each(function() {
                $(this).initAutocomplete();
            });
            $(this).find("select[combobox]").each(function() {
                $(this).combobox();
            });
        }).dialog({
            autoOpen: true,
            resizable: false,
            draggable: false,
            height: 450,
            width: 680,
            modal: true,
            buttons: [
                {
                    text: lang['common']['submit'],
                    click: function() {
                        $(this).find("form").submit();
//					$(this).dialog("close");
                    }
                },
                {
                    text: lang['common']['close'],
                    click: function() {
                        $("#dialog-quickly_add").remove();
                    }
                }
            ]
        });
    }

    //显示销售单状态信息
    $.quicklyShowSaleType = function(obj) {
        var sale_order_id = $(obj).parent().find("#sale_order_id").val();
        if (sale_order_id > 0) {
            $("<div id='dialog-sale_state'></div>").remove();
            $("<div id='dialog-sale_state'></div>").load('index.php/SaleOrder/quicklyShowSaleType/id/' + sale_order_id).dialog({
                autoOpen: true,
                resizable: false,
                height: 600,
                width: 720,
                modal: true
            });
        }

    }

    $.quicklyMore = function(obj) {
        var table_obj = $(obj).parents("table:first").next();
        if (table_obj.css("display") == "none") {
            $(obj).html(lang['common']['close']);
            table_obj.show();
        } else {
            $(obj).html(lang['common']['add_open']);
            table_obj.hide();
        }
    }

    $.langTab = function(event, langSet) {
        if (event.shiftKey && event.which == 76) {
            if ($.browser.msie) {
                var txt = document.selection.createRange().text;
            } else {
                var txt = window.getSelection().toString();
            }
            if (txt == '') {
                return;
            }
            txt = encodeURI(txt);
            addTab(APP + '/Lang/index/search_form/1/lang_value_' + langSet + '/' + txt, lang['basic']['lang_index'], 1);
            return false;
        }
    }

})(jQuery);


/* 公共扩展 */
jQuery.fn.extend({
    initAutocomplete: function() {
        $(this).unbind("click").unbind("blur").autocomplete("destroy");
        var url = this.attr("url");
        var where = this.attr("where");
        this.addClass("ac_input detail_input");
        if (where == undefined)
            where = '';
        var _input = this;
        var search = this.attr('search');
        var _appendto = _input.attr("appendto") ? $dom.find("#" + _input.attr("appendto")) : _input.prev();
        var _itemto = _input.attr("itemto") ? _input.attr("itemto") : $tab_id;
        $(this).autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: url,
                    type: "post",
                    dataType: "json",
                    data: "term=" + request.term + "&where=" + encodeURIComponent(where),
                    success: function(data) {
                        _input.removeClass("ui-autocomplete-loading");
                        if ($.type(data) == "null") {
                            _input.autocomplete("close");
                            if (search == 1) {
                                _appendto.val(' ').trigger("change");
                            } else {
                                _appendto.val('').trigger("change");
                            }
                        }
                        else if (data.length == 1 && _input.val().toUpperCase() == data[0].value.toUpperCase()) {
                            _input.val(data[0].value);
                            _appendto.val(data[0].id).trigger("change");
                            response(data);
                        } else {
                            if (request.term == _input.val()) {
                                if (search == 1) {
                                    _appendto.val(' ').trigger("change");
                                } else {
                                    _appendto.val('').trigger("change");
                                }
                            }
                            response(data);
                        }
                    }
                });

            },
            select: function(event, ui) {
                _appendto.val(ui.item.id).trigger("change");
            },
            appendTo: "#" + _itemto
        })
                .click(function() {
            if ($(this).autocomplete("widget").is(":visible")) {
                $(this).autocomplete("close");
                return;
            }
            $(this).autocomplete("search", " ");
        })
                .blur(function() {
            if (this.value == "")
                _appendto.val('');
        })
    },
    tableClick: function() {
        $(this).find("tr").live('click', function() {
            $(this).toggleClass("selected_tr")
        });
    },
    bandCache:function(){
      $.sumDetailCache();  
    },
    bandTotalMethod: function() {
        $dom.find('input[row_total],input[row_total_money],input[row_total_disount],span[class*=del],input[row_per]').die().live("keyup", function() {
            $.sumTotal(this);
        });
        $dom.find('input[row_tax]').die().live("keyup", function() {
            $.sumTax();
        });
    },
    bandProductMethod: function() {
        $dom.find('input[jqproc]').die().live("change", function() {
            //换货的时候,获取可销售库存的规格
            if ($(this).attr('flow') == 'sale_return')
                $.getProductInfoById(this, 'sale_return');
            else
                $.getProductInfoById(this);
        });
        //选择仓库更新明细仓库
        $dom.find('input[jqware]').die().live("change", function() {
            $.getWareByMainWear(this);
        });
        //发票选择产品号
        $dom.find('input[jqip]').die().live("change", function() {
            $.getInvoiceProductInfoById(this);
        });
        //条形码
        /*$dom.find('input[jqbarcode]').die().live("keydown",function(e){
         $.barcode(e);
         event.stopPropagation(); 
         });*/
    },
    UploadFile: function() {
        var _file = $(this);
        if ($.browser.msie) {
            _file.addClass('other');

        } else {
            _file.css({border: "0px", margin: "0px", padding: "0px", width: "0", height: "0"});
            _file.after('<input type="button" value="' + lang['common']['upload_file'] + '" class="other" onmouseout="this.className=\'other\'" onmouseover="this.className=\'mover_other\'">');
            var obj = _file.next();
            obj.bind('click', function() {
                _file.trigger('click');
            });
        }
    }
});

/* 公共方法 */
(function($) {
    $.widget("ui.combobox", {
        _create: function() {
            var input,
                    self = this,
                    select = this.element.hide(),
                    selected = select.children(":selected"),
                    value = selected.val() ? selected.text() : "",
                    wrapper = this.wrapper = $("<span>")
                    .addClass("ui-combobox")
                    .insertAfter(select);
            input = $("<input>")
                    .appendTo(wrapper)
                    .val(value)
                    .addClass("ui-combobox-input ac_input")
                    .autocomplete({
                delay: 0,
                minLength: 0,
                source: function(request, response) {
                    var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                    response(select.children("option").map(function() {
                        var text = $(this).text();
                        if (this.value && (!request.term || matcher.test(text)))
                            return {
                                label: text.replace(
                                        new RegExp(
                                        "(?![^&;]+;)(?!<[^<>]*)(" +
                                        $.ui.autocomplete.escapeRegex(request.term) +
                                        ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                        ), "<strong>$1</strong>"),
                                value: text,
                                option: this
                            };
                    }));
                },
                select: function(event, ui) {
                    ui.item.option.selected = true;
                    self._trigger("selected", event, {
                        item: ui.item.option
                    });
                    select.trigger("change");
                },
                change: function(event, ui) {
                    if (!ui.item) {
                        var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                                valid = false;
                        select.children("option").each(function() {
                            if ($(this).text().match(matcher)) {
                                this.selected = valid = true;
                                return false;
                            }
                        });
                        if (!valid) {
                            // remove invalid value, as it didn't match anything
                            $(this).val("");
                            select.val("");
                            input.data("autocomplete").term = "";
                            return false;
                        }
                    }
                },
                appendTo: select.attr("itemto") ? "#" + select.attr("itemto") : "#" + $tab_id
            })
                    .addClass("ui-widget ui-widget-content ui-corner-left")
                    .click(function() {
                if (input.autocomplete("widget").is(":visible")) {
                    input.autocomplete("close");
                    return;
                }
                input.autocomplete("search", "");
                input.focus();
            });

            input.data("autocomplete")._renderItem = function(ul, item) {
                return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append("<a>" + item.label + "</a>")
                        .appendTo(ul);
            };


        },
        destroy: function() {
            this.wrapper.remove();
            this.element.show();
            $.Widget.prototype.destroy.call(this);
        }
    });

    // 查看链接
    $.view = function(obj) {
        var url = $(obj).attr("url");
        var title = $(obj).attr("title");
        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            data: "accessCheck=1&referer=js",
            cache: false,
            async: false,
            success: function(result) {
                if (result.status == 1) {
                    $tabs.tabs("add", url, title);
                } else {
                    success(result);
                }
            }
        });
    }
    // 修改链接
    $.edit = function(obj) {
        var url = $(obj).attr("url");
        var title = $(obj).attr("title");
        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            data: "accessCheck=1&referer=js",
            cache: false,
            async: false,
            success: function(result) {
                if (result.status == 1) {
                    linkTab(url, title, 1);
                } else {
                    success(result);
                }
            }
        });
    }
    // 删除链接
    $.cancel = function(obj) {
        var url = $(obj).attr("url");
        if (!url) {
            $("#dialog-error").dialog({height: 140, resizable: false, modal: true});
            return false;
        }
        $("#dialog:ui-dialog").dialog("destroy");
        $("#dialog-confirm").dialog({
            resizable: false,
            height: 140,
            modal: true,
            buttons: {
                "是": function() {
                    $(this).dialog("close");
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: "referer=js",
                        dataType: "json",
                        cache: false,
                        async: false,
                        success: function(result) {
                            success(result);
                        }
                    });
                },
                "否": function() {
                    $(this).dialog("close");
                }
            }
        });
    }
    //展开弹窗
    $.showDialog = function(obj) {
        var url = $(obj).attr("url");
        if (!url) {
            $("#dialog-error").dialog({height: 140, resizable: false, modal: true});
            return false;
        }
        var id = $(obj).attr("dialogid");
        if (id) {
            var dialog_id = id;
            $("#" + dialog_id).remove();
        }
        $("<div id='" + dialog_id + "'></div>").load(url).dialog({
            resizable: false,
            height: 480,
            width: document.documentElement.clientWidth * 0.9,
            modal: true,
            buttons: {
                "关闭": function() {
                    $(this).dialog("close");
                }
            }
        });
    }
    // 还原链接
    $.restore = function(obj) {
        var url = $(obj).attr("url");
        var title = $(obj).attr("title");
        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            cache: false,
            async: false,
            success: function(result) {
                success(result);
            }
        });
    }

    //复制行并清空 （流程中使用)
    $.copyRowWithFrom = function(obj) {
        var object_parent = $(obj).parents('table:first').find('tbody');
        var last_tr_obj = $(object_parent).find("tr:last");
        var count = 0;
        var tr_index;
        //取最大索引值
        $(object_parent).find('tr').each(function() {
            tr_index = $.cParseInt($(this).attr('index'));
            if (count < tr_index) {
                count = tr_index;
            }
        });
        count = $.cParseInt(count);
        count += 1;
        var preFix = '<tr index="' + count + '">';
        var suFix = '</tr>';
        var newHtml = preFix + $(obj).parents("table:first").find('.none').html() + suFix;
        newHtml = newHtml.replace(/\[\d+\]/g, "[" + count + "]");
        //插入行	
        if ($(obj).parents('tr:first').attr('index') > 0) {
            $(obj).parents('tr:first').after(newHtml);
            var new_obj = $(obj).parents('tr:first').next();
        } else {
            $(obj).parents('table:first').find('tbody tr:last').after(newHtml);
            var new_obj = $(obj).parents('table:first').find('tbody').find('tr:last');
        }
//		var new_obj = 	$(obj).parents('tr:first').next();
        $(new_obj).find('td[id=span_state]').html(lang['common']['order_normal']);
        ///autocomplete初始化
        $(new_obj).find("input[jqac]").each(function() {
            $(this).initAutocomplete();
        });
        // select 初始化
        $(new_obj).find('select[combobox]').each(function() {
            $(this).parents('td:first').find('.ui-combobox').remove();
            $(this).combobox();
        });
        var last_html = $(new_obj).find('td:last').html().replace('delRowFlowBrf', "delRow");
        $(new_obj).find('td:last').html(last_html);
        return new_obj;
    };
    //复制行但不清空
    $.copyRowWithoutClear = function(obj) {
        var object_parent = $(obj).parents('tr:first');
        var count = $(object_parent).parent('tbody').find("tr").length + 1;
        $(object_parent).parent('tbody').find("tr").each(function() {
            if ($(this).attr("index") >= count) {
                count = $.cParseInt($(this).attr("index")) + 1
            }
            ;
        });
        var preFix = '<tr index="' + count + '">';
        var suFix = '</tr>';
        var newHtml = preFix + $(object_parent).html() + suFix;
        newHtml = newHtml.replace(/\[\d+\]/g, "[" + count + "]");
        $(object_parent).after(newHtml);
        var object_new = $(object_parent).next();
        object_new.find('#after_discount_money').html('');// 编辑时将id input删除	
        object_new.find("input[name*='[id]']").replaceWith('');
        $(object_new).find('input[jqac]').each(function() {
            $(this).initAutocomplete();
        });
        $(object_new).find('select[combobox]').each(function() {
            $(this).parents('td:first').find('.ui-combobox').remove();
            $(this).combobox();
        });
        $.sumTotal(obj);
        return object_new;
    };
    //删除行
    $.delRow = function(obj) {
        var url = $(obj).attr("url");
        var brf = true;
        if (url) {
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: "accessCheck=1&referer=js",
                cache: false,
                async: false,
                success: function(result) {
                    if (result.status != 1) {
                        $("<div>" + result.info + "</div>").dialog({
                            modal: true,
                            resizable: false,
                            buttons: {
                                Ok: function() {
                                    $(this).dialog("close");
                                }
                            }
                        });
                        brf = false;
                    }
                }
            });
        }
        if (brf == false)
            return false;

        var object_parent = $(obj).parent('td').parent('tr');
        var count = $(object_parent).parent('tbody').find("tr[index]").not(".none").length;
        if (count == 1) {
            //先复制一行 
            $.copyRowWithFrom(obj);
        }
        $.sumTotal(obj, 'del');
        $.sumTax();
        $(obj).parent('td').parent('tr').remove();
        return true;
    };
    //删除行--流程验证
    $.delRowFlowBrf = function(obj, id) {
        var url = $dom.find("form").attr("action");
        data = $dom.find("form").serialize();
        data += '&url=' + url + '&self_id=' + id + '&fn=Delete';
        //执行业务规则 
        if ($.confirmBrf(data, 'validBrfDetail')) {
            $.delRow(obj);
        }

        return false;
    };

    $.expand = function(obj) {
        var expand = $(obj).attr("expand");
        var url = $(obj).attr("url");
        var data = $(obj).attr("where");
        var this_tr = $(obj).parents("tr:first");
        var formData = $($dom).find("#search_form").serialize();
        if (expand == 1) {
            $(obj).attr("expand", 0);
            this_tr.find("a span").removeClass("icon-pattern-minus");
            this_tr.find("a span").addClass("icon-pattern-plus");
            this_tr.next().remove();
            this_tr.next().removeClass("b_top_style");
        } else {
            $(obj).attr("expand", 1);
            this_tr.find("a span").removeClass("icon-pattern-plus");
            this_tr.find("a span").addClass("icon-pattern-minus");
            $.ajax({
                type: "POST",
                url: url,
                data: "data=" + encodeURIComponent(data) + "&" + formData,
                dataType: "text",
                cache: false,
                async: false,
                success: function(html) {
                    var show_html = '<tr expandTr="true"><td><span class="icon icon-pattern-open"></span></td><td colspan="20" style="padding-top:8px;">' + html + '</td>';
                    this_tr.next().addClass("b_top_style");
                    this_tr.after(show_html);
                }
            });
        }
    };
    //列表中显示二级列表
    $.showExpand = function(action, show_id, id) {
        // 0隐藏 1展开
        if (action == '') {
            return false;
        }	//AJAX中方法的名字
        var expand = $($dom).find("#" + show_id).attr("expand");
        if (expand == 1) {
            //把+这个样式替换成-样式
            $($dom).find('#' + show_id + ' #expand span').removeClass();
            $($dom).find('#' + show_id + ' #expand span').attr('class', 'icon icon-pattern-minus');
            var colspan = $($dom).find('#' + show_id).find("td").size() - 1;
            //必传字段
            //show_id当前ID名称,colspan上级列的个数 
            var data = "show_id=" + show_id + "&colspan=" + colspan + "&id=" + id;
            // 判断是否存在需要传递表单数据，表单ID为：search_form
            var formData = $($dom).find("#search_form").serialize();
            if (formData) {
                data = data + "&" + formData;
            }
            $.post(APP + "/AjaxExpand/" + action, data, function(data) {
                if (data != false) {
                    data = '<tr id="' + show_id + '_expand_tr" expandTr="true"><td class="t_center"><span class="icon icon-pattern-open"></span></td><td colspan="' + colspan + '"><div class="tablediv" style="overflow: auto; max-height:900px;max-width:1400px;text-align: left;">' + data + '</div></td></tr>';
                    $($dom).find("#" + show_id).after(data);
                }
            });
            $($dom).find("#" + show_id).attr("expand", 0);	//修改展开状态
        } else {
            $($dom).find("#" + show_id).attr("expand", 1);	//修改展开状态 
            $($dom).find("#" + show_id + '_expand_tr').remove() //隐藏展开的内容        				
            //把-这个样式替换成+样式
            $($dom).find('#' + show_id + ' #expand span').removeClass();
            $($dom).find('#' + show_id + ' #expand span').attr('class', 'icon icon-pattern-plus');
        }
    };

    //ajax上传图片
    $.uploadFile = function(obj) {
        var action = $(obj).parents('form').attr('action');
        $(obj).parents('form').find('#upload_error').html('');
        $(obj).parents('form').attr('action', APP + "/AjaxUploadify/uploads");
        $(obj).parents('form').ajaxSubmit({
            dataType: 'json',
            success: function(data) {
                if (data.id != -1) {
                    if (data.relation_type == 10) {
                        $.uploadExcel(data, obj);
                    } else {
                        $.uploadView(data);
                    }
                } else {
                    $(obj).parents('td').find('#upload_error').html(data.error);
                }
            }
        });
        $(obj).parents('form').attr('action', action);
    };
    $.uploadExcel = function(data, obj) {
        var parent = $(obj).parents('td');
        if (data) {
            var str = '<div id="file_upload_' + data.id + '" class="uploadifyQueueItem completed"><span class="fileName">' + data.cpation_name + '(' + data.size + ' KB)' + '</span><span class="percentage"> - 上传成功</span>';
            $(parent).find("#file_uploadQueue").html('').append(str);
            $(obj).parents('tr').find('#file_name').val(data.file_url);
            $(obj).parents('tr').find('input[id*="submit"]').removeAttr('disabled');
        } else {
            $(parent).find('#upload_error').html(data.error);
            $(obj).parents('tr').find('#file_name').val('');
            $(obj).parents('tr').find('#input[id*="submit"]').attr('disabled', 'disabled');
        }
    }

    //上传后图片预览
    $.uploadView = function(data) {
        if (data.id > 0) {
            var str = '<div id="file_upload_' + data.id + '" class="uploadifyQueueItem completed"><span class="fileName">' + data.cpation_name + '(' + data.size + ' KB)' + '</span><span class="percentage"> - 上传成功</span>';
            str += '<span class="cancel"><a href="javascript:;" onclick="$.deleteUpload(' + data.id + ')"><img border="0" src="' + PUBLIC + '/Images/Default/close_gray.png"></a></span>';
            str += '<br><img src="' + APP_FILES + data.file + '" border="0" width="100"></div>';
            $dom.find("#file_uploadQueue").append(str);
        } else {
            $dom.find('#upload_error').html(data.error);
        }
        $("input[name='file_upload']").val('');
    }
    //删除图片
    $.deleteUpload = function(id) {
        $.get(APP + '/AjaxUploadify/deletes', {id: id}, function(data) {
            $dom.find("#file_upload_" + id).remove();
        });
    }
    // 设置是否尾箱
    $.setQuantityState = function(obj) {
        if (obj.checked)
            $(obj).prev().val(2);
        else
            $(obj).prev().val(1);
        return;
    }
    //设置是否可用
    $.setIsUse = function(obj) {
        if (obj.checked)
            $(obj).prev().val(1);
        else
            $(obj).prev().val(2);
        return;
    }

    $.getLastQuantity = function(obj, type) {
        var obj_parent = $(obj).parents("tr:first");
        var p_id = $(obj_parent).find("input[name*='product_id]']").val();
        var state = $(obj_parent).find('#mantissa').val();
        if (type) {
            var flow = type;
        } else {
            var flow = $dom.find('#flow').val();
        }
        if (!obj.checked) {
            $.getJSON(APP + '/Ajax/getProductDefaultStorage', {id: p_id, flow: flow, mantissa: state}, function(info) {
                if (info.autocomplete == 1) {
                    if ($(obj_parent).find("input[name*='dozen']").length > 0) {
                        var c_obj = $(obj_parent).find("input[name*='capability']");
                        c_obj.attr({'where': 'product_id=' + p_id + ' and mantissa=' + state, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageCapability'});
                        c_obj.initAutocomplete();
                        c_obj.val('').blur(function() {
                            $.sumTotal(c_obj)
                        });
                        var d_obj = $(obj_parent).find("input[name*='dozen']");
                        d_obj.attr({'where': 'product_id=' + p_id + ' and mantissa=' + state, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageDozen'});
                        d_obj.initAutocomplete();
                        d_obj.val('').focus().trigger("click").blur(function() {
                            $.sumTotal(c_obj)
                        });
//						d_obj.val('').focus().trigger("click").bind("focus",function(){$.sumTotal(d_obj)});
                    } else if ($(obj_parent).find("input[name*='capability']").length > 0) {
                        var c_obj = $(obj_parent).find("input[name*='capability']");
                        c_obj.attr({'where': 'product_id=' + p_id + ' and mantissa=' + state, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageCapability'});
                        c_obj.initAutocomplete();
//						c_obj.val('').blur(function(){$.sumTotal(c_obj)});
                        c_obj.val('').focus().trigger("click").blur(function() {
                            $.sumTotal(c_obj)
                        });
                    }
                } else {
                    if ($(obj_parent).find("input[name*='capability']").length > 0) {
                        var c_obj = $(obj_parent).find("input[name*='capability']");
                        c_obj.autocomplete("destroy").val(info.capability);
//						c_obj.bind("focus",function(){$.sumTotal(c_obj)});
                        c_obj.focus().trigger("click").blur(function() {
                            $.sumTotal(d_obj)
                        });
                    }
                    if ($(obj_parent).find("input[name*='dozen']").length > 0) {
                        var c_obj = $(obj_parent).find("input[name*='dozen']");
                        c_obj.autocomplete("destroy").val(info.dozen);
//						c_obj.bind("focus",function(){$.sumTotal(c_obj)});
                        c_obj.focus().trigger("click").blur(function() {
                            $.sumTotal(d_obj)
                        });
                    }
                }
            })
            return false;
        }
        if (!p_id) {
            return false;
        }
        $.getJSON(APP + '/Ajax/getLastStorage', {id: p_id, state: state}, function(info) {
            if (info) {
//				$(obj_parent).find("input[name*='quantity']").val(1);
                if (info.state == 1) {
                    if ($(obj_parent).find("input[name*='dozen']").length > 0) {
                        $(obj_parent).find("input[name*='capability']").val(info.data.capability);
                        $(obj_parent).find("input[name*='dozen']").val(info.data.dozen);
                        $(obj_parent).find("input[name*='capability']").autocomplete("destroy");
                        $(obj_parent).find("input[name*='dozen']").autocomplete("destroy");
                    } else if ($(obj_parent).find("input[name*='capability']").length > 0) {
                        $(obj_parent).find("input[name*='capability']").val(info.data.capability);
                        $(obj_parent).find("input[name*='capability']").autocomplete("destroy");
                    }
                    $.sumTotal($(obj_parent).find("input[name*='capability']"))
                } else if (info.state == 2) {
                    if ($(obj_parent).find("input[name*='dozen']").length > 0) {
                        var c_obj = $(obj_parent).find("input[name*='capability']");
                        c_obj.attr({'where': 'product_id=' + p_id + ' and mantissa=' + state, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageCapability'});
                        c_obj.initAutocomplete();
//						c_obj.bind("focus",function(){$.sumTotal(c_obj)});
                        c_obj.val('').focus().trigger("click").blur(function() {
                            $.sumTotal(c_obj)
                        });

                        var d_obj = $(obj_parent).find("input[name*='dozen']");
                        d_obj.attr({'where': 'product_id=' + p_id + ' and mantissa=' + state, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageDozen'});
                        d_obj.initAutocomplete();
//						d_obj.bind("focus",function(){$.sumTotal(c_obj)});
                        d_obj.val('').focus().trigger("click").blur(function() {
                            $.sumTotal(d_obj)
                        });
                    } else if ($(obj_parent).find("input[name*='capability']").length > 0) {
                        var c_obj = $(obj_parent).find("input[name*='capability']");
                        c_obj.attr({'where': 'product_id=' + p_id + ' and mantissa=' + state, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageCapability'});
                        c_obj.initAutocomplete();
//						c_obj.bind("focus",function(){$.sumTotal(c_obj)});
                        c_obj.val('').focus().trigger("click").blur(function() {
                            $.sumTotal(c_obj)
                        });
                    }
                }
            } else {
                if ($(obj_parent).find("input[name*='dozen']").length > 0) {
                    $(obj_parent).find("input[name*='capability']").autocomplete("destroy").val('');
                    $(obj_parent).find("input[name*='dozen']").autocomplete("destroy").val('');
                } else if ($(obj_parent).find("input[name*='capability']").length > 0) {
                    $(obj_parent).find("input[name*='capability']").autocomplete("destroy").val('');
                }
            }
        });
    }

    //控制表单计算时的格式，将，转成.号
    $.turnToPointShow = function(input_val) {
        if (!input_val || input_val == undefined) {
            input_val = 0;
        }
        if (digital_format == 'eur') { //欧洲
            input_val = input_val.toString().replace(/\,/g, "");
//			input_val = input_val.toString().replace(/\./g,",");	
            return 	$.cParseFloat(input_val);
        } else {//中国					
            input_val = input_val.toString().replace(/\,/g, "");
            return 	$.cParseFloat(input_val);
        }

    };


    //设置对象HTML
    $.setObjHtml = function(obj_p, obj, str) {
        if (typeof obj_p == undefined || obj_p == '') {
            $dom.find("#" + obj).html(str);
        } else {
            $(obj_p).find("#" + obj).html(str);
        }
    };

    //浮点数字处理
    $.getFloatNum = function(num_val, str_len) {
        if (!str_len) {
            str_len = 2;
        }
        var pow_len = Math.pow(10, str_len);
        num_val = (num_val == '') ? 0 : isNaN(num_val) ? 0 : num_val;
        num_val = Math.round(num_val * pow_len) / pow_len;
        return   num_val;
    };

    //自定义整型转换
    $.cParseInt = function(value) {
        value = parseInt(value);
        value = isNaN(value) ? 0 : value;
        return value;
    };
    //自定义整型转换
    $.cParseIntToOne = function(value) {
        value = parseInt(value);
        value = isNaN(value) ? 1 : value;
        return value;
    };

    //自定义整型转换
    $.cParseFloat = function(value) {
        value = parseFloat(value);
        value = isNaN(value) ? 0 : value;
        return value;
    };

    //控制表单计算时的格式，将，转成.号
    $.turnToPoint = function(input_val) {
        if (!input_val || input_val == undefined) {
            input_val = 0;
            return input_val;
        }

        if (input_val.indexOf(',') > -1 && input_val.indexOf('.') > -1) {
            input_val = 0;
            return input_val;
        }
        input_val = input_val.toString().replace(/\,/g, ".");
        return 	$.cParseFloat(input_val);
    };

    //控制表单输入时的显示格式.转成,号
    $.turnToComma = function(input_val, len) {
        if (!input_val || input_val == undefined) {
            input_val = 0;
        }
        if (digital_format == 'eur') {
//			input_val = input_val.toString().replace(/\./g,",");			
            input_val = $.formatCurrency(input_val, len);
            return input_val;
        } else {
            input_val = input_val.toString().replace(/\,/g, "");
            input_val = $.formatCurrency(input_val, len);
            return input_val;
        }
    };

    /**
     * 将数值四舍五入(保留2位小数)后格式化成金额形式
     *
     * @param num 数值(Number或者String)
     * @return 金额格式的字符串,如'1,234,567.45'
     * @type String
     */
    $.formatCurrency = function(num, len) {
        if (len == '' || len == undefined) {
            len = 0;
        }
        if (digital_format == 'eur') {
            var sign = ',';
            var dcimal_sign = '.'; //小数符号
        } else {
            var sign = ',';
            var dcimal_sign = '.';
        }
        temp_num = String(num).split(dcimal_sign);
        cents = temp_num[1];
        num = temp_num[0];
        var math_sign = '';
        if (num.substring(0, 1) == '-') {
            var math_sign = '-';
            num = num.substring(1);
        }
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
            num = num.substring(0, num.length - (4 * i + 3)) + sign + num.substring(num.length - (4 * i + 3));
        }
        if (cents == undefined) {
            return  math_sign + num;
        } else {
            if (len && cents.length < len) {
                for (var j = 0; j < (len - cents.length); j++) {
                    cents += 0;
                }
            } else if (len && cents.length > len) {
                cents = cents.substring(0, len);
            }
            return math_sign + num + dcimal_sign + cents;
        }
    }

    // 设置 money 显示格式
    $.showEurMoney = function(str, str_len) {
        str = this.getFloatNum(str, str_len + 2);	// 先保留 +1位的小数
        if (!str_len) {
            str_len = 2;
        }
        str = str.toFixed(str_len);
        str = str.replace(".", ",");
        return str;
    };

    // 总合计(改良后sumAll,只对当前修改的行进行比较差异，不遍历所有的行)
    /*
     $.sumTotal = function(obj,type) {			
     obj				= $(obj).parents('tr:first');	
     //	合计中的数量	
     var obj_tfoot	= $(obj).parents('table:first').find('tfoot');
     var factory_id	= $(obj).find("#factory_id").val();
     var currency_id	= $(obj).find("#currency_id").val();   
     var factory_name= $(obj).find("#span_fac_name").html();    
     var sum_qn 		= $.turnToPointShow(obj_tfoot.find('#total_row_total').html()!=undefined ? obj_tfoot.find('#total_row_total').html() : obj_tfoot.find('#total_row_orders_total').html());	
     var sum_money	= $.turnToPointShow(obj_tfoot.find('#total_total_money').html());// 	合计中的金额		
     var old_data	= $(obj).find('span[id^=org_qn_data]').html(); // 修改前的数量及单价		
     var qn			= $.turnToPoint($(obj).find('#quantity').val());	 // 修改后的数量
     var price		= $.turnToPoint($(obj).find('#price').val());	 // 修改后的单价
     var capability	= $(obj).find("#capability").val() == undefined ? 1 : $.turnToPoint($(obj).find("#capability").val());//获取包数
     var dozen 		= $(obj).find("#dozen").val() == undefined ? 1: $.turnToPoint($(obj).find("#dozen").val());//获取打数
     var pieces	 	= $(obj).find("#pieces").val()== undefined ? 1 : $.turnToPoint($(obj).find("#pieces").val());//获取支数		
     var dif_money	= 0;
     var dif_qn		= 0;	
     var dif_row_qn	= 0;		
     var new_qn		= qn * capability * dozen * pieces; // 修改后数量
     var new_money	= new_qn * price ;				// 修改后金额			
     var new_row_qn	= qn// 修改后数量 	
     if (type == 'del') { // 删除
     dif_money = 0;
     dif_qn	  = 0;
     new_money = - new_money;
     new_qn		  =  - new_qn;
     } else {
     if (old_data !='' && old_data != undefined && parseFloat(old_data)) { // 修改前数据
     old_data = old_data.split('_');
     dif_money = old_data[0] * old_data[4]; // 修改前该行的金额合计
     if (dif_money && old_data[1].toString() != '') { // 包
     dif_money = dif_money * old_data[1];
     }
     if (dif_money && old_data[2].toString() != '') { // 打
     dif_money = dif_money * old_data[2];
     }
     if (dif_money && old_data[3].toString() != '') { // 支
     dif_money = dif_money * old_data[3];
     }							
     dif_qn	  = old_data[0] 	//  箱
     * (old_data[1].toString()  == '' ? 1 : old_data[1])	//  包
     * (old_data[2].toString()	== '' ? 1 : old_data[2])	//  打
     * (old_data[3].toString()  == '' ? 1:  old_data[3]);	//  支	
     dif_row_qn	=	old_data[0];						
     }	
     }				
     sum_money = sum_money + new_money - $.cParseFloat(dif_money.toFixed(money_length));	// 最后金额		
     sum_qn	  = sum_qn + new_qn - $.cParseFloat(dif_qn.toFixed(money_length));	
     $(obj).find('#row_total').html($.turnToComma(new_qn.toFixed(money_length), money_length));	
     $(obj).find('#total_money').html($.turnToComma(new_money.toFixed(money_length), money_length));			
     $(obj).find('span[id^=org_qn_data]').html(qn+'_'+capability+'_'+dozen+'_'+pieces+'_'+price);	
     obj_tfoot.find('#total_row_total').html($.turnToComma(sum_qn.toFixed(int_length), int_length));
     obj_tfoot.find('#total_row_orders_total').html($.turnToComma(sum_qn.toFixed(int_length),int_length )); // 订货中明细特殊处理
     obj_tfoot.find('#total_total_money').html($.turnToComma(sum_money.toFixed(money_length), money_length));
     if ($dom.find('#sum_goods_cost').length) {			
     $dom.find('#sum_goods_cost').html($.turnToComma(sum_money.toFixed(money_length), money_length));
     }
     var iva_sum_money = 0;	
     if ($dom.find('#sum_iva_cost').length) {		
     if($dom.find('#iva').val() > 0)	{
     var iva_sum_money = sum_money * ($(document).find('#iva').val()/100);	
     $dom.find('#sum_iva_cost').html($.turnToComma(iva_sum_money.toFixed(money_length), money_length));
     }			
     }		
     if ($(document).find('#sum_total_cost').length) {	
     var sum_total_cost = 	iva_sum_money + sum_money;
     $dom.find('#sum_total_cost').html($.turnToComma(sum_total_cost.toFixed(money_length), money_length));						
     }	
     // 折扣处理
     if ($(obj).find('#after_discount_money').length) {
     $.dealWithDiscount(obj, new_money, type, obj_tfoot);
     }
     
     sum_qn 		 	= 0;
     $(obj).parents('tbody').find("input[id='quantity']").each(function(){
     sum_qn += Number(this.value);
     });	
     if (type == 'del'){
     sum_qn 			-= Number($(obj).find("input[id='quantity']").val());
     }
     obj_tfoot.find('#total_quantity').html(sum_qn, int_length);
     };
     */

    // 处理折扣金额
    $.dealWithDiscount = function(obj, new_money, type, obj_tfoot) {
        var discount = $.turnToPoint($(obj).find('#discount').val());// 	合计中的金额		
        var org_new_money = $.turnToPointShow($(obj).find('#after_discount_money').html()); // 原折后金额
        var sum_after_dis_money = $.turnToPointShow(obj_tfoot.find('#total_after_discount_money').html());//折后金额合计	
        var preferential_money = $.turnToPoint($dom.find('#pr_money').val());//优惠后金额
        var old_need_get_money = $.turnToPointShow($dom.find('#old_need_get_money').val());//预付款	
        if (discount && type != 'del') { // 折扣大于0
            if (discount > 100 || discount < 0) {
                $(obj).find('#discount').val('');
                $(obj).find('#discount').focus();
                discount = 0;
            }
            new_money = new_money * (100 - discount) / 100;
        } else if (type == 'del') { //删除明细
            new_money = 0;
        }
        sum_after_dis_money = sum_after_dis_money + new_money - org_new_money;
        // 折后金额
        $(obj).find('#after_discount_money').html($.turnToComma(new_money.toFixed(money_length), money_length));
        // 折后金额合计
        obj_tfoot.find('#total_after_discount_money').html($.turnToComma(sum_after_dis_money.toFixed(money_length), money_length));
        // 计算优惠后金额		 		
        $dom.find('#after_preferential_money').html($.turnToComma((sum_after_dis_money - preferential_money).toFixed(money_length), money_length));
        var pay_type = ['', 'pay_cash_money', 'pay_bill_money', 'pay_bank_money'];
        //应收款		   
        var inputmoney = $dom.find("#" + pay_type[$("#pay_paid_type").val()]).val();
        $dom.find('#need_get_money').html($.turnToComma((sum_after_dis_money + old_need_get_money - preferential_money - inputmoney).toFixed(money_length), money_length));
    }

    // 处理优惠后金额
    $.dealWithPM = function(objId, type) {
        var preferential_money = $.turnToPoint($dom.find('#pr_money').val());//优惠金额		
        if ($.turnToPointShow($dom.find('td[total_col_dis_money]').html())) {
            var sum_after_dis_money = $.turnToPointShow($dom.find('td[total_col_dis_money]').html());//优惠后金额	
        } else {
            var sum_after_dis_money = $.turnToPointShow($dom.find('td[total_col_money]').html());//优惠后金额	
        }
        var old_need_get_money = $.turnToPointShow($dom.find('#old_need_get_money').val());//预付款	 
        if (typeof(objId) == 'undefined') {
            var inputmoney = 0
        } else {
            var inputmoney = objId && $.turnToPointShow($dom.find('#' + objId).val());//优惠后金额	 
        }
        $dom.find('#after_preferential_money').html($.turnToComma((sum_after_dis_money - preferential_money).toFixed(money_length), money_length));		//销售单金额  
        if (type != 'undate') {
            $dom.find('#need_get_money').html($.turnToComma((sum_after_dis_money + old_need_get_money - preferential_money - inputmoney).toFixed(money_length), money_length));		//应收款
        }
        if (!objId) {
            $dom.find('.panes_sale').find('div:visible').find('input[name*="_money"]').trigger('keyup');
        }
    }

    //销售单实际金额
    $.realMoneyWithSale = function(sum_after_dis_money, preferential_money) {
        var old_need_get_money = $.turnToPointShow($dom.find('#old_need_get_money').val());//预付款	 
        var pay_type = ['', 'pay_cash_money', 'pay_bill_money', 'pay_transfer_money'];
        //应收款		
        var inputmoney = $dom.find("#" + pay_type[$("#pay_paid_type").val()]).val();
        if (inputmoney == '' || typeof(inputmoney) == 'undefined') {
            inputmoney = 0;
        }
        $dom.find('#need_get_money').html($.turnToComma((sum_after_dis_money + old_need_get_money - preferential_money - inputmoney).toFixed(money_length), money_length));
    }

    //处理预付款
    $.advenceMoney = function(money, type) {
        var old_need_get_money = $.turnToPointShow($dom.find('#old_need_get_money').val());//历史金额	 
        money = $.turnToPoint(money);//历史金额	   
        if (type == 'add' || type == 'addsale') {
            $dom.find('#old_need_get_money').val((old_need_get_money - money).toFixed(money_length));		//销售单金额
        } else if (type == 'del') {
            $dom.find('#old_need_get_money').val((old_need_get_money + money).toFixed(money_length));		//销售单金额
        }
        if (type == 'addsale') {
            $.dealWithPM('', 'undate');
        } else {
            $.dealWithPM();
        }
    }

    // 处理优惠后金额
    $.dealWithIva = function() {
        var iva = $.turnToPoint($dom.find('#iva').val());//优惠金额		
        var sum_goods_cost = $.turnToPointShow($dom.find('#sum_goods_cost').html());//优惠后金额				
        var sum_iva_cost = sum_goods_cost * iva / 100;
        var sum_total_cost = sum_iva_cost + sum_goods_cost;
        $dom.find('#sum_iva_cost').html($.turnToComma(sum_iva_cost.toFixed(money_length), money_length));
        $dom.find('#sum_total_cost').html($.turnToComma(sum_total_cost.toFixed(money_length), money_length));
    }
    $.sumDetailCache = function(obj){
        var _cache   = function(obj_row){
            //行箱数
            var quantity    = $.cParseFloat($(obj_row).find('input[name*=quantity]').val());
            $(obj_row).data('quantity',quantity);
            //行折扣
            var discount    = $.cParseFloat($(obj_row).find('input[row_total_disount]').val()) == 0 ? 1 : (100 - $.cParseFloat($(obj_row).find('input[row_total_disount]').val())) / 100;
            $(obj_row).data('discount',discount);
            //行总数量
            var total_row_qn= new Array();
            $(obj_row).find('input[row_total]').each(function(){
                total_row_qn.push($.cParseFloat($(this).val()));
            });
            $(obj_row).data('total_row_qn',eval(total_row_qn.join("*")));
            //行总金额
            var total_row_money = $.cParseFloat($(obj_row).find('input[row_total_money]').val()) != 0 && ($.cParseFloat(eval(total_row_qn.join("*"))) + '*' + $.cParseFloat($(obj_row).find('input[row_total_money]').val()));
            total_row_money     = eval(total_row_money)
            $(obj_row).data('total_row_money',total_row_money);
            //行合计折扣金额
            var total_row_dis_money = $.cParseFloat(discount) != 0 && (total_row_money + '*' + $.cParseFloat(discount));
            $(obj_row).data('total_row_dis_money',$.cParseFloat(eval(total_row_dis_money)));
            //行尺寸
            var per_size    = $.turnToPointShow($(obj_row).find('input[name*="per_size]"]').val()) * $.turnToPointShow(quantity);
            $(obj_row).data('per_size',per_size);
            //行总重量
            var per_capability  = $.turnToPointShow($(obj_row).find('input[name*="per_capability]"]').val()) * $.turnToPointShow(quantity);
            $(obj_row).data('per_capability',per_capability);
        };
        if(typeof(obj)==='undefined'){
            $('.detail_list tr:visible').each(function(){
                _cache($(this));
            });
        }else{
            _cache($(obj));
        }
    }
    //计算列表合计和行合计
    $.sumTotal = function(obj, type) {
        var parent = $(obj).parent('td').parent('tr');
        var tbody_parent = $(obj).parent('td').parent('tr').parent('tbody');
        var total_row_money = $(parent).data('total_row_money');//行金额合计
        var total_quantity  = $(parent).data('quantity');
        var total_row_qn = $(parent).data('total_row_qn');//列数量合计
        var total_row_dis_money = $(parent).data('total_row_dis_money');//行折扣合计
        var flow = $dom.find('#flow').val();
        $.sumDetailCache($(parent));
        ///行数量差异
        total_quantity  = $(parent).data('quantity')-total_quantity;
        //总数量差异
        total_row_qn    = $(parent).data('total_row_qn')-total_row_qn;
        //行合计金额差异
        total_row_money = $(parent).data('total_row_money')-total_row_money;
        //计算行合计折扣金额差异
        total_row_dis_money = $(parent).data('total_row_dis_money')-total_row_dis_money;
        if (flow == 'orders')
            $(parent).find('input[name*="sumq]"]').val($(parent).data('total_row_qn'));
        $(parent).find('td[total_row_qn]').html($.turnToComma($.cParseFloat($(parent).data('total_row_qn')).toFixed(int_length), int_length));//总数量
        //如果装柜,去判断是否装柜数量大于订货数量,有则提示错误
        if (flow == 'loadcontainer') {
            var order_id = $(parent).find('#order_id').val();
            if ($.cParseFloat($(parent).data('total_row_qn')) > 0 && type != 'del' && order_id > 0) {
                $(parent).find('td[total_row_qn]').bind('change', checkLoadQuantity(obj, $(parent).data('total_row_qn'), 'loadcontainer'));
            }
        }
        //修改订货单,不允许小于装柜数量
        if (flow == 'orders') {
            var orders_id = $dom.find('input[name="id"]').val();
            if ($.cParseFloat($(parent).data('total_row_qn')) > 0 && type != 'del' && orders_id > 0) {
                $(parent).find('td[total_row_qn]').bind('change', checkLoadQuantity(obj, $(parent).data('total_row_qn'), 'orders'));
            }
        }
        $(parent).find('td[total_row_money]').html($.turnToComma($.cParseFloat($(parent).data('total_row_money')).toFixed(money_length), money_length));//总金额
        $(parent).find('td[total_row_dis_money]').html($.turnToComma($.cParseFloat($(parent).data('total_row_dis_money')).toFixed(money_length), money_length)); //折后金额
        
        var total_col_qn = $.turnToPointShow($(parent).parents('table:first').find('tfoot td[total_col_qn]').html())+total_row_qn;
        var total_col_money = $.turnToPointShow($(parent).parents('table:first').find('tfoot td[total_col_money]').html())+total_row_money;
        var total_col_dis_money = $.turnToPointShow($(parent).parents('table:first').find('tfoot td[total_col_dis_money]').html())+total_row_dis_money;
        var col_quantity = $.turnToPointShow($(parent).parents('table:first').find('tfoot td[total_quantity]').html())+total_quantity;
        var per_size = 0;
        var per_capability = 0;
        // IE8 及以下版本 选择器 用* 速度很慢 稍作修改 ----zmx 2013-04-15
        var obj_row = type == 'del' ? $(tbody_parent).find('tr:visible').not(parent) : $(tbody_parent).find('tr:visible');
        $(obj_row).each(function() {
            var tr_prent = $(this);
//            total_col_qn    += ($(this).data('total_row_qn'));
//            total_col_money += ($(this).data('total_row_money'));
//            total_col_dis_money += ($(this).data('total_row_dis_money'));
//            col_quantity    += ($(this).data('quantity'));
            per_size        += ($(this).data('per_size'));
            per_capability  += ($(this).data('per_capability'));
        });
        //底部合计
        $(tbody_parent).parent('table').find('tfoot').find('td[total_col_qn]').html($.turnToComma(eval(total_col_qn).toFixed(int_length), int_length));//总数量
        $(tbody_parent).parent('table').find('tfoot').find('td[total_quantity]').html($.turnToComma(eval(col_quantity).toFixed(money_length), money_length));//总箱数
        $(tbody_parent).parent('table').find('tfoot').find('td[total_col_money]').html($.turnToComma(eval(total_col_money).toFixed(money_length), money_length));//总金额
        $(tbody_parent).parent('table').find('tfoot').find('td[total_col_dis_money]').html($.turnToComma(eval(total_col_dis_money).toFixed(money_length), money_length));//折后金额
        $(tbody_parent).parent('table').find('tfoot').find('td[col_per_size]').html($.turnToComma(eval(per_size).toFixed(money_length), money_length));//尺寸
        $(tbody_parent).parent('table').find('tfoot').find('td[col_per_capability]').html($.turnToComma(eval(per_capability).toFixed(money_length), money_length));//重量
        if (flow == 'sale')
            $.dealWithPM();
        $.sumFactoryTotal($(parent),type);
    }
    //厂家合计
    $.sumFactoryTotal   = function(parent,type){
        //厂家装柜小计
        if ($dom.find('.load_list').html() != null) {
            if ($.cParseInt($(parent).find('#factory_id').val()) != 0) {
                var row_quantity = $(parent).data('quantity');
                var factory_id = $(parent).find('#factory_id').val();
                var currency_id = $(parent).find('#currency_id').val();
                var factory_name = $(parent).find('#span_fac_name').html();
                var ikey = factory_id + '_' + currency_id;
                var iquantity = 0;
                var isumquantity = 0;
                var imoney = 0;
                //当厂家小计已存在的话,累积
                if ($dom.find("#" + ikey + '_tr').size() > 0) {
                    var fac_quantity = 0;
                    var fac_subquantity = 0;
                    var fac_submoney = 0;
                    $dom.find('input[id=factory_id][value=' + factory_id + ']').parent('td').parent('tr').find('input[id=currency_id][value=' + currency_id + ']').each(function() {
                        if (type == 'del')
                            var parent_row = $(this).parent('td').parent('tr').not(parent);
                        else
                            var parent_row = $(this).parent('td').parent('tr');
                        fac_quantity += $(this).parents('tr:first').data('quantity');
                        fac_subquantity += $(this).parents('tr:first').data('total_row_qn');
                        fac_submoney += $.cParseFloat($.turnToPointShow($(parent_row).find('td[total_row_money]').html()));
                    });
                    //如果数量0了以后不显示该行
                    if (fac_quantity == 0 && fac_subquantity == 0) {
                        $dom.find("#" + ikey + '_tr').remove();
                    }
                    $dom.find("#" + ikey + '_quantity').html($.turnToComma(fac_quantity.toFixed(money_length), money_length));
                    if ($(parent).parents('table:first').find('tfoot').find('td[total_col_qn]').html() != null) {
                        $dom.find("#" + ikey + '_sumquantity').html($.turnToComma(fac_subquantity.toFixed(int_length), int_length));
                    } else {
                        $dom.find("#" + ikey + '_sumquantity').html($.turnToComma(fac_quantity.toFixed(int_length), int_length));
                    }
                    $dom.find("#" + ikey + '_money').html($.turnToComma(fac_submoney.toFixed(money_length), money_length));
                } else {
                    if (row_quantity > 0) {
                        //如果不存在新增一行厂家小计
                        var html_str = '';
                        var row_total_quantity = $(parent).data('total_row_qn');
                        var row_total_money = $.cParseFloat($.turnToPointShow($(parent).find('td[total_row_money]').html()));
                        html_str += '<tr id="' + ikey + '_tr">';
                        html_str += '<td  id="' + ikey + '_factory" class="t_left">' + factory_name + '</td>';
                        if ($(parent).parents('table:first').find('tfoot').find('td[total_col_qn]').html() != null) {
                            html_str += '<td  id="' + ikey + '_quantity" >' + $.turnToComma(row_quantity.toFixed(money_length), money_length) + '</td>';
                            html_str += '<td  id="' + ikey + '_sumquantity">' + $.turnToComma(row_total_quantity.toFixed(int_length), int_length) + '</td>';
                        } else {
                            html_str += '<td  id="' + ikey + '_sumquantity">' + $.turnToComma(row_quantity.toFixed(int_length), int_length) + '</td>';
                        }
                        html_str += '<td  id="' + ikey + '_money">' + $.turnToComma(row_total_money.toFixed(money_length), money_length) + '</td>';
                        html_str += '</tr>';
                        $dom.find("#total_factory").after(html_str);
                    }
                }
                $dom.find('#total_factory_quantity').html($(parent).parents('table:first').find('tfoot td[total_quantity]').html());
                if ($(parent).parents('table:first').find('tfoot').find('td[total_col_qn]').html() != null) {
                    $dom.find('#total_factory_sumquantity').html($(parent).parents('table:first').find('tfoot td[total_col_qn]').html());
                } else {
                    $dom.find('#total_factory_sumquantity').html($(parent).parents('table:first').find('tfoot td[total_quantity]').html());
                }
                $dom.find('#total_factory_money').html($(parent).parents('table:first').find('tfoot td[total_col_money]').html());
            }
        }
    }

    //流程获取产品的信息
    $.getProductInfoById = function(obj, type) {
//		var id		  	= $(obj).val();
        var obj_parent = $(obj).parents('tr:first');
        var id = $(obj_parent).find('input[name*="product_id]"]').val();
        var color_id = $(obj_parent).find('input[name*="color_id]"]').val();
        var size_id = $(obj_parent).find('input[name*="size_id]"]').val();
        var client_id = 0;
        var flow = $dom.find('#flow').val();
        //如果是特殊操作,取调整日期
        var adjust_date = $dom.find('input[name*="adjust_date"]').val();
        var state = $(obj_parent).find('#mantissa').val() == undefined ? 1 : $(obj_parent).find('#mantissa').val();
        if (flow == 'instock') {
            var currency_id = $(obj_parent).find('#currency_id').val();
        } else {
            var currency_id = $dom.find('#currency_id').val();
        }
        if (id > 0) {
            $(obj_parent).find('#autoshow_img').attr('pid', id);
            client_id = $dom.find('#client_id').val();
            $.getJSON(APP + '/Ajax/getProductInfo', {id: id, currency_id: currency_id, client_id: client_id, flow: flow, color_id: color_id, size_id: size_id, type: type, adjust_date: adjust_date, mantissa: state}, function(data) {
                $(obj_parent).find('#span_product_name').html(data.product_name);
                if (flow == 'sale' || type == 'sale_return') {
                    if (data.storage_color > 0) {
                        //颜色
//							if($(obj).attr('id')=='product_id'){
//								$(obj_parent).find('input[name*=color_id]').val('');
//								$(obj_parent).find('input[name=color_name]').val('');
//							}
                        $(obj_parent).find('input[name=color_name]').attr({'where': 'product_id=' + id, 'jqac': true, 'url': APP + '/AutoComplete/saleroductColor'});
                        $(obj_parent).find('input[name=color_name]').initAutocomplete();
                    }
                    if (data.storage_size > 0) {
//							if($(obj).attr('id')=='product_id'){
//								//尺码
//								$(obj_parent).find('input[name*=size_id]').val('');
//								$(obj_parent).find('input[name=size_name]').val('');
//							}
                        $(obj_parent).find('input[name=size_name]').attr({'where': 'product_id=' + id, 'jqac': true, 'url': APP + '/AutoComplete/saleroductSize'});
                        $(obj_parent).find('input[name=size_name]').initAutocomplete();
                    }
                }
                if (data.autocomplete == 1) {
                    var where = ' and 1 ';
                    if (color_id > 0)
                        where += ' and color_id=' + color_id;
                    if (size_id > 0)
                        where += ' and size_id=' + size_id;
                    if ($(obj_parent).find("input[name*='dozen']").length > 0) {
                        var c_obj = $(obj_parent).find("input[name*='capability']");
                        c_obj.attr({'where': 'product_id=' + id + ' and mantissa=' + state + where, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageCapability'}).val('');
                        c_obj.initAutocomplete();
                        c_obj.blur(function() {
                            $.sumTotal(c_obj)
                        });
                        var d_obj = $(obj_parent).find("input[name*='dozen']");
                        d_obj.attr({'where': 'product_id=' + id + ' and mantissa=' + state + where, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageDozen'}).val('');
                        d_obj.initAutocomplete();
                        d_obj.blur(function() {
                            $.sumTotal(c_obj)
                        }).trigger("click");
                    } else if ($(obj_parent).find("input[name*='capability']").length > 0) {
                        var c_obj = $(obj_parent).find("input[name*='capability']");
                        c_obj.attr({'where': 'product_id=' + id + ' and mantissa=' + state + where, 'jqac': true, 'url': APP + '/AutoComplete/lastStorageCapability'}).val('');
                        c_obj.initAutocomplete();
                        c_obj.blur(function() {
                            $.sumTotal(c_obj)
                        }).trigger("click");
                    }
                } else {
                    if ($(obj_parent).find('input[name*=capability]').length > 0)
                        $(obj_parent).find('input[name*=capability]').unbind("click").unbind("blur").autocomplete("destroy").addClass('ac_input').val(data.capability);
                    if ($(obj_parent).find('input[name*=dozen]').length > 0)
                        $(obj_parent).find('input[name*=dozen]').unbind("click").unbind("blur").autocomplete("destroy").addClass('ac_input').val(data.dozen);
                }
                if ($dom.find('#client_id').length > 0) {
                    $(obj_parent).find('input[name*=price]').val(data.edml_sale_price);
                } else {
                    $(obj_parent).find('input[name*=price]').val(data.edml_instock_price);
                }
                if (data.show_delivery > 0) {
                    if ($(obj_parent).find("input[name*='per_size]']").length > 0)
                        $(obj_parent).find("input[name*='per_size]']").val(data.edml_per_size);
                    if ($(obj_parent).find("input[name*='per_capability]']").length > 0)
                        $(obj_parent).find("input[name*='per_capability]']").val(data.edml_weight);
                }
                $(obj_parent).find('input[name*=price]').trigger('keyup');
                $(obj_parent).find('#quantity_state').attr('checked', false);
            });
        }
        ;
    }

    /*************配货******************/
    $.getWareByMainWear = function(obj) {
        var id = $(obj).val();
        if (id > 0) {
            $.post(APP + '/Ajax/getWareName', {id: id}, function(data) {
                $dom.find('input[name=warehouse_name]').each(function() {
                    $(this).val(data);
                    $(this).prev('input').val(id);
                });
            });
        }
    }
    /*******************************/
    $.invoiceProductEnabled = function(obj) {
        $(obj.form).find("input[name*='product_no]']").val('').prev().val('');
        $(obj.form).find("input[name*='product_no]']").removeAttr("disabled").removeClass("disabled").attr({"jqac": true})
                .each(function() {
            $(this).initAutocomplete();
        })
    }
    //获取发票产品信息
    $.getInvoiceProductInfoById = function(obj) {
        var id = $(obj).val();
        var obj_parent = $(obj).parents('tr:first');
        if (id > 0) {
            $.getJSON(APP + '/Ajax/getInvoiceProductInfo', {id: id}, function(data) {
                $(obj_parent).find('input[name*=product_id]').val(data.id);
                $(obj_parent).find('input[name*=product_name]').val(data.product_name);
                $(obj_parent).find('#span_product_name').html(data.product_name);
                $(obj_parent).find('#span_invoice_ingredient').html(data.ingredient);
            });
        }
    }
    //发票计算税额和发票总金额
    $.sumTax = function() {
        var iva = $.cParseFloat($dom.find('input[name=iva]').val());
        var total_money = $dom.find('.detail_list tr:last').find('td[total_col_dis_money]').html();
        if (total_money == null || total_money == undefined) {
            total_money = $dom.find('.detail_list tr:last').find('td[total_col_money]').html();
        }
        //货值
        $dom.find('td[tax_quantity]').html(total_money);
        //税额
        var tax_cost = (iva / 100 * $.turnToPointShow(total_money)).toFixed(money_length);
        $dom.find('td[tax_cost]').html($.turnToComma(tax_cost, money_length));
        //发票总金额
        var tax_total_cost = ($.turnToPointShow(total_money) + parseFloat(tax_cost)).toFixed(money_length);
        $dom.find('td[tax_total_cost]').html($.turnToComma(tax_total_cost, money_length));
    }

    $.autoShow = function(obj, module_name) {
        var pid = parseInt($(obj).attr("pid"));
        if (isNaN(pid) == true)
            return;
        $("#autoShowDiv").dialog("destroy").html('loading...');
        var oft = $(obj).offset();
        $("#autoShowDiv").load(APP + '/AutoShow', {"id": pid, "module": module_name}).dialog({
            autoOpen: true,
            resizable: false,
            show: "Fold",
            width: 680,
            height: 500,
            position: [oft.left + 20, oft.top - 150]
        }).mouseleave(function() {
            $(this).dialog("destroy");
        });
//		$("#autoShowDiv").parents("div:first").attr('class','autoshow');
        return false;

    }
    // 通过条形码新增一行
    $.addRowByBarcode = function(obj) {
        var barcode = $.trim($(obj).val());
        var flow = $.trim($dom.find('#flow').val());
        var parent = $(obj).parent('td').parent('tr').parents('table').parent('td');
        if (barcode.length > 0) {
            $.getJSON(APP + '/Ajax/getProductByBarcode', {barcode: barcode}, function(data) {
                if (data) {
                    var first_obj = $(parent).find('.detail_list').find('tbody').find('tr:visible:first');
                    var list_row = $(parent).find('.detail_list').find('tbody').find('tr:visible').size();
                    for (i = 1; i <= list_row; i++)
                    {
                        if (first_obj.find("input[name*='product_id]']").val() < 1 || !first_obj.find("input[name*='product_no]']").val()) {
                            first_obj = first_obj;
                        } else {
                            if (i == list_row) {
                                first_obj = first_obj;
                            } else {
                                first_obj = first_obj.next();
                            }
                        }
                    }
                    if (first_obj.find("input[name*='product_id]']").val() < 1 || !first_obj.find("input[name*='product_no]']").val()) {
                        var obj = first_obj;
                    } else {
                        var obj = $.copyRowWithFrom($(first_obj).find('td:last').find('span[class*="icon-add-plus"]'));
                    }
                    $(obj).find('#barcode').html(barcode);
                    $(obj).find('input[name*="product_id]"]').val(data.p_id).trigger('change');
                    $(obj).find('input[name*="product_no]"]').val(data.product_no);
                    $(obj).find('#span_product_name').html(data.product_name);
                    // 设置产品颜色尺码(产品不绑定颜色及尺码)
                    if (data.color_id > 0) {
                        $(obj).find('input[name*="color_id]"]').val(data.color_id);
                        data.color_id != null && $(obj).find('input[name*="color_name"]').val(data.color_name);
                    }
                    if (data.size_id > 0) {
                        $(obj).find('input[name*="size_id]"]').val(data.size_id);
                        data.size_id != null && $(obj).find('input[name*="size_name"]').val(data.size_name);
                    }
                    // 设置产品颜色属性(产品绑定颜色及尺码)
//					if (($(obj).find('input[name*="color_id]"]').length>0 || $(obj).find('input[name*="span_id]"]').length>0) && (data.color_id < 1 || data.size_id <1)) {
//						var row_id = obj.attr('index');
//						if(!row_id) row_id = 1;		
//						if(flow =='sale' ) {						
//							var ajax_fn = 'getFlowPropertiesForSale';
//						} else{
//							var ajax_fn = 'getFlowProperties';
//						}																	
//						$.getJSON(APP+'/Ajax/'+ajax_fn,{id:data.p_id,row_id:row_id,color_id:data.color_id,size_id:data.size_id},function(data){
//						if(data.state==true){				
//								if(data.color != undefined){
//									$(obj).find("#span_color").html(data.color);
//								}
//								if(data.size  != undefined){
//									$(obj).find("#span_size").html(data.size);
//								}
//							}
//						});										
//					}						
                }
            });
        }
    };
    //基础信息列表排序
    $.sortBy = function(field, sort) {
        $dom.find('#search_form').find("input[name='_sort'],input[name='_order']").remove();
        var str = '<input type="hidden" name="_sort" value="' + sort + '"><input type="hidden" name="_order" value="' + field + '">';
        $dom.find('#search_form').append(str).submit();
    }
})(jQuery);


